package com.byit.utils;

import java.util.*;

/**
 * App端，参数防篡改工具类
 * @author wangx
 */
public class TamperUtil {
    /**
     * 按key的英文字母从小到大排列
     *
     * @param map
     * @return
     */
    public static String sortMapByKeyForString(Map<String, String> map) {

        StringBuilder sb = new StringBuilder();
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());

        sortMap.putAll(map);

        Set<String> keySet = sortMap.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            sb.append(key + "=" + sortMap.get(key)+ "&");
        }
        return sb.toString().substring(0, sb.toString().length() - 1);
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
        sortMap.putAll(map);
        return sortMap;
    }

    static class MapKeyComparator implements Comparator<String> {
        @Override
        public int compare(String str1, String str2) {
            return str1.compareTo(str2);
        }
    }
}